package cn.chenhao.basic.util;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.IOException;

public class SendMsgUtil {

    private static final String UID = "lzchenhao";
    private static final String KEY = "d41d8cd98f00b204e980";

    /**
     * 发送短信的接口
     * @param phone 接收短信的手机号，多个号码用逗号分割 最多100个
     * @param message 短信内容
     */

    public static void send(String phone,String message){

        try {
            HttpClient client = new HttpClient();
            PostMethod post = new PostMethod("http://gbk.api.smschinese.cn");
            post.addRequestHeader(
                    "Content-Type",
                    "application/x-www-form-urlencoded;charset=utf8");//在头文件中设置转码
            NameValuePair[] data = {
                    new NameValuePair(
                            "Uid",// 你的短信接口的账号
                            UID),
                    new NameValuePair(
                            "Key",// 短信接口的授权码
                            KEY),
                    new NameValuePair(
                            "smsMob",// 收件人
                            phone),
                    new NameValuePair(
                            "smsText",// 短信内容
                            message)};
            post.setRequestBody(data);

            client.executeMethod(post);
            Header[] headers = post.getResponseHeaders();
            int statusCode = post.getStatusCode();
            System.out.println("statusCode:" + statusCode);
            for (Header h : headers) {
                System.out.println(h.toString());
            }
            String result = new String(post.getResponseBodyAsString().getBytes("utf8"));
            System.out.println(result); //打印返回消息状态

            post.releaseConnection();
        }
        catch (IOException e) {
            e.printStackTrace();
        }

    }

}


